module Utils where

import Data.Coerce (coerce)

import GHCJS.DOM.Document
import GHCJS.DOM.Element (setAttribute)
import GHCJS.DOM.Node
import GHCJS.DOM.WebGLRenderingContextBase
import GHCJS.DOM.HTMLCanvasElement (getContext)
import GHCJS.DOM.Types hiding (Text)

import qualified JavaScript.TypedArray.Internal as J
import qualified JavaScript.TypedArray as J
import qualified GHCJS.Marshal as J
import qualified JavaScript.Array as J
import qualified GHCJS.Types as J

import Control.Monad
import Linear

initGL :: Document -> IO WebGLRenderingContextBase
initGL doc = do
  Just body <- getBody doc
  Just canvas <- createElement doc (Just "canvas")
  setAttribute canvas "width" "400"
  setAttribute canvas "height" "400"
  _ <- appendChild body (Just canvas)
  WebGLRenderingContextBase <$> getContext (coerce canvas) "webgl"

m44ToList :: M44 a -> [a]
m44ToList (V4 x y z w) = concat $ v4ToList <$> [x, y, z, w]
  where v4ToList (V4 a b c d)= [a, b, c, d]

doubles2Float32Array :: [Double] -> IO J.Float32Array
doubles2Float32Array = J.float32ArrayFrom . J.fromList <=< mapM J.toJSVal

matReady :: M44 Double -> IO J.Float32Array
matReady = doubles2Float32Array . m44ToList . transpose

angle2radian :: Double -> Double
angle2radian x = pi * x / 180.0
